package com.sh.wy.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sh.util.Result;
import com.sh.wy.system.entity.SaveRoleIdsByUserIdParam;
import com.sh.wy.system.entity.SysRole;
import com.sh.wy.system.entity.SysUser;
import com.sh.wy.system.entity.SysUserParam;
import com.sh.wy.system.service.ISysRoleService;
import com.sh.wy.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author 世豪学Java
 * @since 2023-12-14
 */
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户管理")
public class SysUserController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ISysRoleService roleService;

    //新增用户
    @ApiOperation("新增用户")
    @PostMapping
    //不需要加路径，请求不同
    public Result addUser(@RequestBody SysUser user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        boolean save = userService.save(user);
        if (save){
            return Result.success();
        }
        return Result.error(500,"添加失败");
    }

    //编辑用户
    @ApiOperation("修改用户")
    @PutMapping
    public Result editUser(@RequestBody SysUser user){
        boolean update = userService.updateById(user);
        if (update){
            return Result.success();
        }
        return Result.error(500,"修改失败");
    }

    //删除用户
    @ApiOperation("删除用户")
    @DeleteMapping("/{userId}")
    public Result deleteUser(@PathVariable("userId") Integer userId){
        boolean remove = userService.removeById(userId);
        if (remove){
            return Result.success();
        }
        return Result.error(500,"删除失败");
    }

    //获取用户列表
    @ApiOperation("获取用户列表")
    @GetMapping("/list")
    public Result list(SysUserParam sysUserParam){

        IPage<SysUser> list = userService.list(sysUserParam);
        return Result.success(list);
    }

    //查询所有角色并选中用户拥有的角色
    @ApiOperation("查询所有角色并选中用户拥有的角色")
    @GetMapping("/checkRoles/{userId}")
    public Result checkRoles(@PathVariable Integer userId){
        List<SysRole> list = roleService.checkRoles(userId);
        return Result.success(list);
    }

    //保存用户拥有的角色信息
    @ApiOperation("保存用户拥有的角色信息")
    @PutMapping("/saveRoleIdsByUserId")
    public Result saveRoleIdsByUserId(@RequestBody SaveRoleIdsByUserIdParam param){
        boolean save = roleService.saveRoleIdsByUserId(param);
        if(save){
            return Result.success();
        }
        return Result.error(500,"保存角色信息失败");
    }
}
